<template>
  <div class="div" style="width:100%;height: 100%;" v-loading="false" element-loading-background="rgba(0, 0, 0, 0.2)">
    <div class="Training-results-panel">
      <div class="results-panel-Breadcrumb">
        <img class="panelImg" src="@/assets/img/other/icon-任务动态.png" />
        <div class="results-panel-route">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: item.path }" v-for="(item, index) in State.Breadcrumbs" :key="index"
              @click="ChangeRouter(index)">{{ item.pathname }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <el-button v-if="State.StatePanel == 0" class="ExcelBtn" @click="exportExcel">导出</el-button>
      </div>
      <ResultDetails v-if="State.StatePanel == 1 && State.ModelType == '1'" :ResultDetails="State.ResultDetails">
      </ResultDetails>
      <Disassembly v-if="State.StatePanel == 1 && State.ModelType == '0'" :ResultDetails="State.ResultDetails">
      </Disassembly>
      <FaultDiagnosis v-if="State.StatePanel == 1 && State.ModelType == '12'" :ResultDetails="State.ResultDetails">
      </FaultDiagnosis>
      <!-- 从学生教师端的任务处查看成绩详情 -->
      <Maintain v-if="State.StatePanel == 1 && State.ModelType == '8'" :ResultDetails="State.ResultDetails"></Maintain>
      <!-- 103任务详情 -->
      <Radar103 v-if="State.StatePanel == 1 && State.ModelType == '9'" :ResultDetails="State.ResultDetails"></Radar103>
      <!-- 状态为7新版本的拆装-拆装 -->
      <DismountingDiagnosis v-if="State.StatePanel == 1 && State.ModelType == '7' && Type7 == '拆装'"
        :ResultDetails="State.ResultDetails">
      </DismountingDiagnosis>
      <!-- StructureDiagnosis -->
      <!-- 状态为7新版本的拆装-结构 -->
      <StructureDiagnosis v-if="State.StatePanel == 1 && State.ModelType == '7' && Type7 == '结构'"
        :ResultDetails="State.ResultDetails">
      </StructureDiagnosis>
      <!-- <div class="results-text">
      <div class="results-button"
        ><span class="results-span-exit">返回</span></div>
    </div> -->
    </div>
    <!-- 成绩栏 -->
    <div class="results-panel-table" v-if="State.StatePanel === 0">
      <el-table :data="State.SetAllResult" style="width: 100%" height="92%" ref="table">
        <el-table-column prop="userName" label="姓名" min-width="15%">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ scope.row.userName }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="用时" min-width="21%">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ TimeChange(scope.row.useTime) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" min-width="21%">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ scope.row.score }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="finishTime" label="完成时间" min-width="21%">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ renderTimes(scope.row.finishTime) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column fixed="right" prop="option" label="操作" min-width="22%">
          <template #default="scope">
            <el-button @click="FindScoreDetails(scope.row)" class="results-button-detailed">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 导出字段模板 -->
    <div class="results-panel-table" style="position: absolute; top:-200%;">
      <el-table :data="State.SetAllResult" style="width: 100%" height="92%" ref="table" id="outDetails">
        <el-table-column prop="userName" label="姓名" min-width="15%" :fixed="State.fixs">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ scope.row.userName }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="用时" min-width="21%" :fixed="State.fixs">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ TimeChange(scope.row.useTime) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" min-width="21%" :fixed="State.fixs">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ scope.row.score }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="finishTime" label="完成时间" min-width="21%" :fixed="State.fixs">
          <template #default="scope">
            <el-form :model="scope.row">
              <el-form-item>
                <span>{{ renderTimes(scope.row.finishTime) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 导出字段模板 -->
  </div>
</template>

<script>
import bus from "@/bus";
import router from '../router'
import ResultDetails from "@/components/compon/ResultDetails.vue";
import Disassembly from "@/components/compon/Disassembly.vue";
import FaultDiagnosis from '@/components/compon/FaultDiagnosis.vue'
import Maintain from '@/components/compon/Maintain.vue'
import Radar103 from '@/components/compon/Radar103.vue'
import DismountingDiagnosis from '@/components/compon/DismountingDiagnosis.vue'
import StructureDiagnosis from '@/components/compon/StructureDiagnosis.vue'
import { ElMessage } from 'element-plus'
import { postData } from "@/assets/js/pubilcs.js";
import { defineComponent, reactive, toRef, toRefs, ref, nextTick, watch, onMounted } from "vue";
import { renderTimes, TimeChange } from "@/assets/js/pubilcs.js";
import FileSaver from "file-saver";
import { read, utils, WorkSheet, writeFile, writeFileXLSX, write } from "xlsx";
import HomeContent from '../components/HomeContent'
export default defineComponent({
  name: "Model",
  components: {
    ResultDetails,
    Disassembly,
    FaultDiagnosis,
    Maintain,
    Radar103,
    DismountingDiagnosis,
    StructureDiagnosis,
  },
  props: {
    SetResuAllData: {
      type: Array,
      default: "",
    },
  },
  emits: ['SetChangePanel'],
  setup(props, ctx) {
    // 拆装结构类型
    let Type7 = ref('')
    let aaa = ref(false)
    let State = reactive({
      fixs: true,
      SetAllResult: [],
      ResultDetails: [],
      StatePanel: 0,
      Breadcrumbs: [],
      ChangePanel: 1,
      Loading: true,
      timer: '',
      ModelType: 999,
    })
    //模拟Loading效果
    State.timer = setTimeout(function () {
      State.SetAllResult = props.SetResuAllData[0].SetAllResult
      State.Loading = false
      clearTimeout(State.timer)
      State.timer = null
    }, 200);
    watch(() => props.SetResuAllData, (val, old) => {
      //State.SetResuAllData = val
      // State.Loading=true
    },
      { deep: true }
    )
    //设定导航与显示的面板
    State.Breadcrumbs = props.SetResuAllData[0].Breadcrumbs
    State.ChangePanel = props.SetResuAllData[0].ChangePanel
    //判断是学生面板就直接显示学生的成绩
    if (props.SetResuAllData[0].Panel === "Student") {
      State.StatePanel = 1
      // State.ModelType = props.SetResuAllData[0].SetAllResult.type
      State.ResultDetails = props.SetResuAllData[0].SetAllResult
    }
    let table = ref(null)
    if (props.SetResuAllData[0].Panel !== 'Student') {
      nextTick(() => {
        table.value.doLayout()
      })
    }
    // 导出
    function exportExcel() {
      State.fixs = false
      //不加判断table表格导出会有两份数据，是因为fixed造成的，所以要筛选去重
      // 判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去，
      var fix = document.querySelector('.el-table__fixed');
      var exportTable;
      if (fix) {
        exportTable = utils.table_to_book(document.querySelector('#outDetails').removeChild(fix));
        document.querySelector('#outDetails').appendChild(fix);
      } else {
        exportTable = utils.table_to_book(document.querySelector('#outDetails'));
      }
      var exportTableOut = write(exportTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([exportTableOut], { type: 'application/octet-stream' }), '实训成绩.xlsx')
      } catch (e) { if (typeof console !== 'undefined') console.log(e, exportTableOut) }
      State.fixs = true
      return exportTableOut
    }
    //面包屑跳转实现
    function ChangeRouter(index) {

      if (index === 0) {
        if (State.StatePanel === 0) {
          ctx.emit("SetChangePanel", 1)
        }
        if (State.StatePanel === 1) {
          ctx.emit("SetChangePanel", 1)
        }
      }
      if (index === 1) {
        if (State.StatePanel === 0) {
          return
        }
        if (State.StatePanel === 1) {
          if (props.SetResuAllData[0].Panel === 'Student') {
            return
          }
          State.StatePanel = 0
          State.Breadcrumbs = [
            {
              pathname: '实训任务',
              path: '/SimulationTasks'
            },
            {
              pathname: '实训成绩',
              path: '/SimulationTasks'
            },
          ]
          nextTick(() => {
            table.value.doLayout()
          })
        }
      }
    }

    //查询成绩详情
    // 目前详情分类是按照模块的类型 sessionStorage.getItem("ModelType") 来获取的，对应的StandaloneMenu文件夹里的Templet字段
    // 详情分教师端，学生端，专家端，还有比赛端的，根据以下的函数根据不同类型跳转到不同的项目详情
    // 目前的详情页面分类在CompetitionDetails界面中有清晰的分类注释
    function FindScoreDetails(row) {
      State.Breadcrumbs = [
        {
          pathname: '实训任务',
          path: '/SimulationTasks'
        },
        {
          pathname: '实训成绩',
          path: '/SimulationTasks'
        },
        {
          pathname: '成绩详情',
          path: '/SimulationTasks'
        }
      ]
      postData("/api/TrainingResult/GetById", JSON.stringify({ Id: row.trainingResultId }), sessionStorage.getItem("token")).
        // postData("/api/TrainingResult/GetById", JSON.stringify({ Id: 4725 }), sessionStorage.getItem("token")).
        then(function (res) {
          // console.log(JSON.parse(res.result.result.record));
          // 这里是详情的总体数据，不同的项目，数据可能不同，需要特别注意下返回的orders和record这两个数据参数
          console.log('??????????????????????详情跳转', res.result.result);
          State.ResultDetails = res.result.result

          console.log(res.result.result.productId, ':', State.ResultDetails, JSON.parse(State.ResultDetails.orders));
          // Type7.value = JSON.parse(State.ResultDetails.orders).Type
          if (JSON.parse(State.ResultDetails.orders) != null) {

            if (State.ModelType == 7) {
              if (JSON.parse(State.ResultDetails.orders).Type) {
                console.log(res.result.result.productId, ':', State.ResultDetails, JSON.parse(State.ResultDetails.orders));
                Type7.value = JSON.parse(State.ResultDetails.orders).Type
                aaa.value = true
                console.log('是否是结构拆装1111', Type7.value);
              } else {
                JSON.parse(State.ResultDetails.orders).Veidoos.forEach(element => {
                  if (element.Name == '工具使用' || element.Name == '操作流程' || element.Name == '操作规范' || element.Name == '时间效率') {
                    Type7.value = '拆装'
                  } else {
                    Type7.value = '结构'
                  }
                });
              }
            }
            if (State.ModelType == 8) {
              HomeContent.Default.Synthetical.value = JSON.parse(State.ResultDetails.orders).Record.Synthetical
              HomeContent.Default.workOrderSheet.value = JSON.parse(State.ResultDetails.orders).Record.WorkOrderSheet
              HomeContent.Default.resultInfo.value = JSON.parse(State.ResultDetails.orders)
              HomeContent.Default.ratingForm.value = JSON.parse(State.ResultDetails.orders).Record.RatingForm
              HomeContent.Default.FaultRepair.value = JSON.parse(State.ResultDetails.orders).Record.FaultRepair
            }
            State.StatePanel = 1
            State.ChangePanel = 2

            HomeContent.Default.operateRecord.value = JSON.parse(res.result.result.record)
            console.log('222222222222222');

            // State.ModelType = res.result.result.type



            // if (res.result.result.record != null) {
            //   State.StatePanel = 1
            //   State.ChangePanel = 2
            // }
          } else {
            ElMessage({
              message: '暂无数据！',
              type: 'warning'
            })
          }

          // if (res.result.result.record == null) {
          //   ElMessage({
          //     message: '暂无数据！',
          //     type: 'warning'
          //   })
          // }
        })
        .catch((error) => {

        });
    }
    onMounted(() => {
      State.ModelType = sessionStorage.getItem("ModelType")
      console.log('模块类型', State.ModelType, props.SetResuAllData[0].Panel);

      if (State.ModelType == 7) {
        console.log('props.SetResuAllData', props.SetResuAllData);
        if (props.SetResuAllData[0].Panel == 'Student') {
          let content = JSON.parse(props.SetResuAllData[0].SetAllResult.orders)
          console.log('content777777', content, content.Type);
          // Type7.value = content.Type
          if (content.Type) {
            Type7.value = content.Type
          } else {
            content.Veidoos.forEach(element => {
              // console.log('7777element', element);
              if (element.Name == '工具使用' || element.Name == '操作流程' || element.Name == '操作规范' || element.Name == '时间效率') {
                Type7.value = '拆装'
              } else {
                Type7.value = '结构'
              }
            });
          }
        }
      }
      if (props.SetResuAllData[0].Panel === "Student") {
        if (State.ModelType == 8) {
          HomeContent.Default.Synthetical.value = JSON.parse(State.ResultDetails.orders).Record.Synthetical
          HomeContent.Default.workOrderSheet.value = JSON.parse(State.ResultDetails.orders).Record.WorkOrderSheet
          HomeContent.Default.resultInfo.value = JSON.parse(State.ResultDetails.orders)
          HomeContent.Default.ratingForm.value = JSON.parse(State.ResultDetails.orders).Record.RatingForm
          HomeContent.Default.FaultRepair.value = JSON.parse(State.ResultDetails.orders).Record.FaultRepair
        }
      }

    })
    return {
      State,
      FindScoreDetails,
      table,
      ChangeRouter,
      renderTimes,
      TimeChange,
      exportExcel,
      Type7,
      aaa,
    };

  },

});
</script>
<style lang="less">
.Training-results-panel {
  position: absolute;
  width: 1720px;
  height: calc(100% - 10%);
  left: 160px;
  top: 100px;
  background: #ffffff;
  border-radius: 16px;
}

.panelImg {
  position: absolute;
  width: 24px;
  height: 24px;
  max-width: 100%;
  max-height: 100%;
  left: 22px;
  top: 21px;
}

.results-panel-route {
  position: absolute;
  left: 55px;
  top: 25px;
  z-index: 1;
}

.Training-results-panel .results-button {
  position: absolute;
  left: 1600px;
  top: 20px;
  width: 130px;
  height: 30px;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../assets/img/other/icon-返回-normal.png") 45px 0px;
  background-repeat: no-repeat;
  background-size: 21%;
  -moz-background-size: 21%;
  color: #81859c;
  cursor: pointer;
  z-index: 1;
}

.Training-results-panel .results-span-exit {
  margin-left: -90px;
  margin-bottom: 5px;
}

.Training-results-panel .results-button:hover {
  color: #0974d8;
  width: 130px;
  height: 30px;
  background: url("../assets/img/other/icon-返回-hover.png") 45px 0px;
  background-repeat: no-repeat;
  background-size: 21%;
  -moz-background-size: 21%;

}

.results-text i {
  position: absolute;
  font-size: 21px;
  padding-left: 5px;
}

.results-panel-table {
  position: absolute;
  width: 1690px;
  height: 890px;
  left: 160px;
  top: 145px;
  background: #ffffff;
  border-radius: 16px;
}

.results-panel-table .el-table {
  text-align: center;
  left: 15px;
  top: 30px;
}

.results-panel-table .cell {
  text-align: center;
}

.results-panel-table .results-button-detailed {
  width: 80px;
  height: 40px;
  border-radius: 10px;
  border: 1px solid #E6E7EBFF;
}

.results-button-detailed:hover {
  background: linear-gradient(90deg, #807de1, #218cde);
}

.results-panel-table .el-table__body-wrapper::-webkit-scrollbar {
  width: 7px;
  background-color: #f5f5f5;
}

.results-panel-table .el-table__body-wrapper::-webkit-scrollbar-track {
  box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  background-color: #f5f5f5;
}

.results-panel-table .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 1.5px rgba(0, 0, 0, 0.2);
  background-color: rgba(230, 232, 236, 1);
  background-color: #f2f3f5;
}

.results-panel-table .el-button:hover {
  color: #ffffff;
}

.results-panel-Breadcrumb {
  width: 100%;
  height: 60px;
}

.results-panel-table .el-form-item {
  margin-bottom: 0px;
}

.ExcelBtn {
  position: absolute;
  top: 20px;
  right: 40px;
  z-index: 999;
}
</style>
